﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZX.BLL.Extend;
using ZX.DBModule;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace ZX.Web.UI.Controls
{
    public class TreeView : Literal
    {
        private string _tableName = "";
        [Description("数据来源的表名")]
        public string TableName
        {
            get { return _tableName; }
            set { _tableName = value; }
        }

        private string _caption = "";
        [Description("文本")]
        public string Caption
        {
            get { return _caption; }
            set { _caption = value; }
        }

        [Description("长名称")]
        public string LCaption
        {
            get;
            set;
        }
        private string _key = "";
        [Description("主键")]
        public string Key
        {
            get { return _key; }
            set { _key = value; }
        }
        private string _parentKey = "";
        [Description("父节点主键")]
        public string ParentKey
        {
            get { return _parentKey; }
            set { _parentKey = value; }
        }
        private string _path = "";
        [Description("节点路径")]
         public string path
        {
            get { return _path; }
            set { _path = value; }
        }
        private bool _isAllowCheck = false;
        [Description("是否允许多选")]
        public bool AllowCheck
        {
            get { return _isAllowCheck; }
            set { _isAllowCheck = value; }
        }
        private int _IsOutDepartment = 0;
        [Description("组织架构类型")]
        public int IsOutDepartment
        {
            get { return _IsOutDepartment; }
            set { _IsOutDepartment = value; }
        }
        private Guid _userID = Guid.Empty;
        [Description("外部人员ID")]
        public Guid userID
        {
            get { return _userID; }
            set { _userID = value; }
        }
        private int _IsVirtual=0;
        [Description("是否虚拟部门")]
        public int IsVirtual
        {
            get { return _IsVirtual; }
            set { _IsVirtual = value; }
        }
        private string _Condition = "";
        [Description("自定义查询条件")]
        public string Condition
        {
            get { return _Condition; }
            set { _Condition = value; }
        }


        /// <summary>
        /// 实体类
        /// </summary>
        public string Entity
        {
            get
            {
                return ParentPage.GetStringFromQueryString("entity", "");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public Guid FunctionID
        {
            get
            {
                return ParentPage.GetGuidFromQueryString("functionid");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public BasePage ParentPage
        {
            get
            {
                return this.Page as BasePage;
            }
        }

        public string DeptPath(IList<TreeViewData> list)
        {
            IList<ZX.EHR.Library.SysRoleFunction> list1 = (new ZX.BLL.BUser()).GetRoleFunction((this.Page as BasePage).UserId, this.FunctionID);
            if (list1.Count == 0)
                return "@001";
            else
            {
                int deptType = 0;
                var _DeptID = ParentPage.EmpPropertyValues.DeptID;
                var dept = list.Where(p => p.Key.ToString() == _DeptID).First();
                IList<TreeViewData> _list = list.Where(p => dept.LCaption.Contains(p.LCaption)).ToList();

                return _list.Where(p => p.DeptType == 0).ToList()[0].Path;
            }
            //return "@001";

        }

        public void GetDeptType(out int deptType, int rangeType)
        {
            switch (rangeType)
            {
                case 0: //本人
                    deptType = 0;
                    break;
                case 1://本部门
                    deptType = 1;
                    break;
                case 2://
                    deptType = 2;
                    break;
                case 3:
                    deptType = 3;
                    break;
            }
            deptType = 4;
        }

        /// <summary>
        /// 获取部门过滤条件
        /// </summary>
        /// <returns></returns>
        public string GetDeptCondition()
        {
            IList<ZX.EHR.Library.SysRoleFunction> list = (new ZX.BLL.BUser()).GetRoleFunction(this.ParentPage.UserId, this.FunctionID);
            string condition = "";
            foreach (var e in list)
            {
                if (e.OperateRangeType == "" || e.OperateRangeType=="2")//全部
                {
                    condition =condition ==""?"1=1": " or 1=1";
                }

                if (e.OperateRangeType.Trim() == "1")//本部门
                {
                    ZX.EHR.Library.DatDepartment dept = this.ParentPage._bll.GetEntityBySqlComm<ZX.EHR.Library.DatDepartment>(string.Format("select * from DatDepartment where DeptID = '{0}'", this.ParentPage.EmpPropertyValues.DeptID));
                    condition =(condition==""?"":" or ") + "DeptPath like '" + dept.DeptPath + "%'"; ;
                }

                if (e.OperateRangeType.Trim() == "5") //本大区
                {
                    ZX.EHR.Library.DatDepartment dept = this.ParentPage._bll.GetEntityBySqlComm<ZX.EHR.Library.DatDepartment>(string.Format("exec sp_getDeptPath '{0}','{1}'",
                                                        this.ParentPage.EmpPropertyValues.DeptID,
                                                        5));
                    condition =(condition==""?"":" or ") + "DeptPath like '" + dept.DeptPath + "%'"; ;
                }

                if (e.OperateRangeType.Trim() == "6")//本分公司
                {
                    ZX.EHR.Library.DatDepartment dept = this.ParentPage._bll.GetEntityBySqlComm<ZX.EHR.Library.DatDepartment>(string.Format("exec sp_getDeptPath '{0}','{1}'",
                                                        this.ParentPage.EmpPropertyValues.DeptID,
                                                        1));
                    condition = (condition == "" ? "" : " or ") + "DeptPath like '" + dept.DeptPath + "%'"; ;
                }

                if (e.OperateRangeType.Trim() == "7")//本中心
                {
                    ZX.EHR.Library.DatDepartment dept = this.ParentPage._bll.GetEntityBySqlComm<ZX.EHR.Library.DatDepartment>(string.Format("exec sp_getDeptPath '{0}','{1}'",
                                    this.ParentPage.EmpPropertyValues.DeptID,
                                    4));
                    condition = (condition == "" ? "" : " or ") + "DeptPath like '" + dept.DeptPath + "%'"; ;
                }

                if (e.OperateRangeType.Trim() == "3")//自定义部门
                {
                    condition = (condition == "" ? "" : " or ") + "'" + e.Depts + "' like '%'+ Cast(DeptID as varchar(38)) + '%'";
                }

            }
            return condition;
        }

        private string CreateOrgData(string DeptPath, IList<TreeViewData> list)
        {
            StringBuilder _orgString = new StringBuilder();
            IList<TreeViewData> rootlist = list.Where(p => p.Path.Contains(DeptPath)==true && p.Path!=DeptPath).ToList();
            if (rootlist == null)
            {
                return _orgString.ToString();
            }
            else
            {
                TreeViewData tv = list.Where(p => p.Path == DeptPath).First();
                IList<TreeViewData> _rootlist = rootlist.Where(p => p.ParentKey == tv.Key).ToList();
                _orgString.Append("<li>\r\n");
                _orgString.Append(tv.Caption);
                if (_rootlist == null)
                {
                    return _orgString.ToString();
                }
                else
                {
                    _orgString.Append("<ul>\r\n");
                    foreach (var _tv in _rootlist)
                    {
                        _orgString.Append(CreateOrgData(_tv.Path,list));
                    }
                    _orgString.Append("</ul>\r\n");
                }
                _orgString.Append("</li>\r\n");
                return _orgString.ToString();
                //throw new Exception(_orgString.ToString());
                //IList<TreeViewData> rootlist
            }
        }

        private string CreateOrgData()
        {
            string sql = "select DeptID as [key],dept.DeptName as Caption,b.deptname as LCaption,ParentID as  ParentKey,DeptPath as [Path],DeptType from DatDepartment dept,dbo.fn_GetOrganizeAll('333FE8ED-CA2A-497A-A88C-3BB4FB3A1A57') b where (IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]='1900-01-01 00:00:00.000') and dept.DeptID=b.id";
            sql = string.Format(sql, DateTime.Now.ToLongTimeString());
            IList<TreeViewData> list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql);
            System.Guid DeptID = (this.Page as BasePage).GetGuidFromQueryString("deptID");
            var data = list.Where(p => p.Key == DeptID);
            if (data.Count() == 0)
            {
                return CreateOrgData("@001", list);
            }
            return CreateOrgData(data.First().Path, list);
        }

        //private string 
        private string createTree(string DeptPath, IList<TreeViewData> list)
        {
            StringBuilder _strHtml = new StringBuilder();
            string sql = "";
            if (AllowCheck)
                _strHtml.Append("<div  id='" + this.ID + "' class='whitebg ygtv-checkbox'>");
            else
                _strHtml.Append("<div  id='" + this.ID + "' class='whitebg'>");
            _strHtml.Append("<ul>");
            //得到一级菜单
            //IList<TreeViewData> rootlist = list.Where(p => p.Path.Split('-').Length == 2).OrderBy(p => p.Path).ToList();
            IList<TreeViewData> rootlist = null;
            //判断是否是外部机构的用户
            //sql="select * from datdepartment where deptid in (select deptid from TrCustomer where  TrCustomerID='"+userID+"')";

            rootlist = list.Where(p => p.Path == DeptPath).OrderBy(p => p.Path).ToList();
            int i = 0;
            if (rootlist != null)
            {
                foreach (TreeViewData tree in rootlist)
                {

                    _strHtml.Append("<li>");
                    if (!AllowCheck)
                    {
                        _strHtml.Append("<span><a href=\"#" + tree.Key + "\" style='display:block;cursor:hand' onclick=\"Native('" + tree.Caption + "','" + tree.Key + "','" + tree.DeptType + "')\">" + tree.Caption + "</a></span>");
                    }
                    else
                    {
                        _strHtml.Append("<a href='#@" + tree.Key + "'>" + tree.Caption + "</a>");
                    }

                    //功能明细
                    AddNode(list, tree.Key, _strHtml);
                    _strHtml.Append("</li>");
                    i++;
                }
            }
            else
            {
                _strHtml.Append("<li>权限不足或数据不存在</li>");
            }
            _strHtml.Append("</ul>");
            _strHtml.Append("</div>");
            return _strHtml.ToString();
        }

        private string CreateDeptTree(bool IsShowSub)
        {
            string sql = "select DeptID as [key],dept.DeptName as Caption,b.deptname as LCaption,ParentID as  ParentKey,DeptPath as [Path],DeptType from DatDepartment dept,dbo.fn_GetOrganizeAll('333FE8ED-CA2A-497A-A88C-3BB4FB3A1A57') b where (IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]='1900-01-01 00:00:00.000') and dept.DeptID=b.id";
            sql = string.Format(sql, DateTime.Now.ToLongTimeString());
            IList<TreeViewData> list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql);
            if (IsShowSub)
            {
                string deptPath = "@001";
                //
                //System.Data.DataRow row =(this.Page as BasePage).User.GetEmployeePostDept();
                //if (row == null)
                //{
                //    //deptPath = "";
                //   return createTree("001", list);
                //}
                //deptPath=row["DeptPath"].ToString();
                System.Data.DataTable dt = (this.Page as BasePage).User.GetUserPostDept();
                StringBuilder _treeHtml = new StringBuilder("");
                if (dt == null)
                {
                    return createTree("001", list);
                }
                else
                {
                    
                    foreach (System.Data.DataRow row in dt.Rows)
                    {
                        deptPath = row["DeptPath"].ToString();
                        string treeTag = createTree(deptPath, list).ToString().Replace("<div  id='treeDiv1' class='whitebg ygtv-highlight'>", "").Replace("<div  id='treeDiv1' class='whitebg'>", "").Replace("</div>", "");
                        treeTag = treeTag.Remove(0, 4);
                        treeTag = treeTag.Remove(treeTag.Length - 5, 5);
                        _treeHtml.Append(treeTag);
                    }
                }
                return "<div  id='treeDiv1' class='whitebg'><ul>" + (_treeHtml) + "</ul></div>";
            }
            else
            {
                return CreateDeptTree();
            }
        }


        private string CreateDeptTree()
        {
            string sql = "select DeptID as [key],dept.DeptName as Caption,b.deptname as LCaption,ParentID as  ParentKey,DeptPath as [Path],DeptType from DatDepartment dept,dbo.fn_GetOrganizeAll('333FE8ED-CA2A-497A-A88C-3BB4FB3A1A57') b where (IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]='1900-01-01 00:00:00.000') and dept.DeptID=b.id";
            sql = string.Format(sql, DateTime.Now.ToLongTimeString());
            IList<TreeViewData> list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql);
            //只需要显示部门树支的实体
            List<string> lstMyDeptEntity = new List<string>() { "V_xzEmpGJJ", "V_xzEmpGJJDeptTotal", "V_wkProjectWorkResult","V_salEmployeeSalaryResult" };
            //菜单里配置参数是否只需要显示部门树支的实体
            bool isOnlyDisplayDept = false;
            if (ParentPage.GetStringFromQueryString("isOnlyDisplayDept", "false") == "true")
            {
                isOnlyDisplayDept = true;
            }
            string deptPath = "@001";
            //配置只显示登录者所属部门的树状,或固定部门分支
            if ((this.Entity.IndexOf("Employee") > 0 || this.Entity.IndexOf("Department") > 0 || this.Entity.IndexOf("Post") > 0 || lstMyDeptEntity.Contains(this.Entity) || isOnlyDisplayDept) && this.FunctionID != Guid.Empty)
            {
                var _DeptID = ParentPage.EmpPropertyValues.DeptID;
                var dept = list.Where(p => p.Key.ToString() == _DeptID).First();
          
                //咨询中心考勤列表固定显示咨询中心分支树状
                if (this.Entity == "V_wkProjectWorkResult")
                {
                    dept = list.Where(p => p.Caption.ToString().Trim() == "咨询中心").First();
                    deptPath = dept.Path;
                }
                else
                {
                    if (dept.LCaption.IndexOf("学校") > 0 || dept.LCaption.IndexOf("分公司") > 0 || dept.LCaption.IndexOf("推广中心") > 0 || dept.LCaption.IndexOf("咨询中心") > 0)
                    {
                        string[] _strDept = dept.LCaption.Replace("->", "_").Split('_');
                        string[] _strPath = dept.Path.Replace("->", "_").Split('-');
                        for (int i = 0; i < _strDept.Length; i++)
                        {
                            if (_strDept[i].IndexOf("分公司") >= 0 || _strDept[i].IndexOf("推广中心") >= 0 || _strDept[i].IndexOf("学校") >= 0 || _strDept[i].IndexOf("咨询中心") >= 0)
                            {
                                deptPath += "-" + _strPath[i];
                                break;
                            }
                            if (i > 0)
                            {
                                deptPath += "-" + _strPath[i];
                            }
                        }
                    }
                }
            }
            //(this.Page as BasePage).EmpPropertyValues.DeptID
            return createTree(deptPath, list);
        }
   

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {

            if (!DesignMode )
            {
                if (this.ParentPage.GetStringFromQueryString("showOrg", "false") == "true")
                {
                    writer.Write(CreateOrgData());
                    //return;
                }
                else
                {
                    if (this.ParentPage.GetStringFromQueryString("right", "N") == "Y")
                    {
                        createRightTree(writer);
                    }
                    else
                    {
                        createTree(writer);
                    }
                }
            }
            else
            {
                writer.Write("树型菜单");
            }
        }

        private void createRightTree(System.Web.UI.HtmlTextWriter writer)
        {
            //只需要显示本部门树支
            string sql = "";
            IList<TreeViewData> list = null;
            StringBuilder sbChilds = new StringBuilder();
            StringBuilder _strHtml = new StringBuilder();
                _strHtml.Append("<div  id='" + this.ID + "' class='whitebg'>");
            _strHtml.Append("<ul>");
            IList<TreeViewData> rootlist = null;

                //sql="select * from datdepartment where deptid in (select deptid from TrCustomer where  TrCustomerID='"+userID+"')";
            sql = "select DeptID as [Key],ParentID as ParentKey,DeptName as Caption,DeptPath as [path],LDeptName as LCaption,DeptType from datdepartment where (IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]='1900-01-01 00:00:00.000') and " + GetDeptCondition();
            list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql).OrderBy(p => p.Path).ToList();
            if(list != null){
                sql = @"select * from (select DeptID as [Key],ParentID as ParentKey,DeptName as Caption,DeptPath as [path],LDeptName as LCaption,DeptType from datdepartment where (IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]='1900-01-01 00:00:00.000') and {0})
a
where a.ParentKey not in (select DeptID as [Key] from datdepartment where (IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]='1900-01-01 00:00:00.000') and {0})";
                sql = string.Format(sql, GetDeptCondition());
                rootlist  = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql).OrderBy(p => p.Path).ToList(); ;
            }
            int i = 0;
            if (rootlist != null)
            {
                foreach (TreeViewData tree in rootlist)
                {

                    _strHtml.Append("<li>");
                    if (!AllowCheck)
                    {
                        _strHtml.Append("<span><a href=\"#" + tree.Key + "\" style='display:block;cursor:hand' onclick=\"Native('" + tree.Caption + "','" + tree.Key + "')\">" + tree.Caption + "</a></span>");
                    }
                    else
                    {
                        _strHtml.Append("<a href='#@" + tree.Key + "'>" + tree.Caption + "</a>");
                    }

                    //功能明细
                    AddNode(list, tree.Key, _strHtml);
                    _strHtml.Append("</li>");
                    i++;
                }
            }
            else
            {
                _strHtml.Append("<li>权限不足或数据不存在</li>");
            }
            _strHtml.Append("</ul>");
            _strHtml.Append("</div>");
            writer.Write(_strHtml.ToString());
            base.Render(writer);
        }


        private void createTree(System.Web.UI.HtmlTextWriter writer)
        {
            //只需要显示本部门树支
            List<string> lstMyDeptEntity = new List<string>() { "V_wkOverTimeLeaveTotal","V_hrEmployee", "V_hrEmployeeDeparture", "V_DatPost", "DatDepartment", "V_wkWorkResult", "V_wkEmpMonthWorkResult", "V_xzEmpInsurance", "V_xzEmpInsuranceDeptTotal", "V_xzEmpGJJ", "V_xzEmpGJJDeptTotal", "V_wkConfirmWorkResult", "V_wkProjectWorkResult" };
            bool IsOnlyMyDept =false;
            if (lstMyDeptEntity.Contains(ParentPage.GetStringFromQueryString("entity", "")) || ParentPage.GetStringFromQueryString("IsOnlyMyDept", "") == "true")
            {
                IsOnlyMyDept = true;
            }
            string sql = "";
            IList<TreeViewData> list = null;
            StringBuilder sbChilds = new StringBuilder();
            StringBuilder _strHtml = new StringBuilder();
            if (AllowCheck)
                _strHtml.Append("<div  id='" + this.ID + "' class='whitebg ygtv-checkbox'>");
            else
                _strHtml.Append("<div  id='" + this.ID + "' class='whitebg'>");
            _strHtml.Append("<ul>");
            //得到一级菜单
            //IList<TreeViewData> rootlist = list.Where(p => p.Path.Split('-').Length == 2).OrderBy(p => p.Path).ToList();
            IList<TreeViewData> rootlist = null;
            //判断是否是外部机构的用户
            if (IsOutDepartment == 0)
            { 
                if (IsOnlyMyDept)  //只需要显示本部门树支
                {
                    writer.Write(CreateDeptTree(ParentPage.GetStringFromQueryString("IsSelfHelp", "false") == "true"));
                    base.Render(writer);
                    return;
                }

                sql = "Exec sp_TreeView '{0}','{1}','{2}','{3}','{4}','{5}'";
                if (TableName.ToLower() == "datdepartment")
                {
                    //Condition = GetDeptCondition();
                    Condition =Condition ==""?"((IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]=''1900-01-01 00:00:00.000''))":"("+Condition+") and ((IsVirtualDepartment<>1 or IsVirtualDepartment is null) and ([ExpireDate]>=getdate() or [ExpireDate]=''1900-01-01 00:00:00.000''))";
                }
                sql = string.Format(sql, TableName, Key, Caption, ParentKey, path, Condition);
                list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql);
                if (list != null)
                {
                    rootlist = list.Where(p => p.Path == "@001").OrderBy(p => p.Path).ToList();
                    if (rootlist.Count == 0)
                    {
                        rootlist = list.Where(p => p.ParentKey == Guid.Empty || p.ParentKey == null).OrderBy(p => p.Caption).ToList();
                    }
                }
            }
            else if (IsVirtual == 1)
            {

                sql = "Exec sp_TreeView '{0}','{1}','{2}','{3}','{4}','IsVirtualDepartment=1'";
                sql = string.Format(sql, TableName, Key, Caption, ParentKey, path);
                list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql);
                rootlist = list.Where(p => p.Path == "@002").OrderBy(p => p.Path).ToList();
            }
            else
            {
                //sql="select * from datdepartment where deptid in (select deptid from TrCustomer where  TrCustomerID='"+userID+"')";
                sql = "select *,LDeptName as LCaption from datdepartment where (IsVirtualDepartment<>1 or IsVirtualDepartment is null)";
                list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql);
                rootlist = list.Where(p => p.Path.Split('-').Length == 2 && (!p.Path.Contains("@001"))).OrderBy(p => p.Path).ToList();

            }
            int i = 0;
            if (rootlist != null)
            {
                foreach (TreeViewData tree in rootlist)
                {

                    _strHtml.Append("<li>");
                    if (!AllowCheck)
                    {
                        _strHtml.Append("<span><a href=\"#" + tree.Key + "\" style='display:block;cursor:hand' onclick=\"Native('" + tree.Caption + "','" + tree.Key + "')\">" + tree.Caption + "</a></span>");
                    }
                    else
                    {
                        _strHtml.Append("<a href='#@" + tree.Key + "'>" + tree.Caption + "</a>");
                    }

                    //功能明细
                    AddNode(list, tree.Key, _strHtml);
                    _strHtml.Append("</li>");
                    i++;
                }
            }
            else
            {
                _strHtml.Append("<li>权限不足或数据不存在</li>");
            }
            _strHtml.Append("</ul>");
            _strHtml.Append("</div>");
            writer.Write(_strHtml.ToString());
            base.Render(writer);
        }

       

        private void AddNode(IList<TreeViewData> list, Guid? key,StringBuilder sb)
        {
            var detail = list.Where(p => p.ParentKey == key).OrderBy(p => p.Path).ToList();
            if (detail.ToList().Count > 0)
            {
                sb.Append("<ul>");
                foreach (TreeViewData v in detail)
                {
                    sb.Append("<li>");
                    if (!AllowCheck)
                    {
                        sb.Append("<span><a href=\"#" + v.Key + "\" style='display:block;cursor:hand' onclick=\"Native('" + v.Caption + "','" + v.Key + "','" + v.DeptType + "')\">" + v.Caption + "</a></span>");
                    }
                    else
                    {
                        sb.Append("<a href='#@" + v.Key + "'>" + v.Caption + "</a>");
                    }
                    AddNode(list, v.Key, sb);
                    sb.Append("</li>");

                }
                sb.Append("</ul>");
            }
            //childName += "</ul>";
          
         
        }

        public string createTreeHtml(string xDeptPath) 
        {
            IList<TreeViewData> list = null;
            IList<TreeViewData> rootlist = null;
            StringBuilder sbChilds = new StringBuilder();
            StringBuilder _strHtml = new StringBuilder();
            string DeptPath = xDeptPath;//"@001-001";


            string sql = "select DeptID as [key],DeptName as Caption,LDeptName as LCaption,ParentID as  ParentKey,DeptPath as [Path],DeptType from datdepartment where (isvirtualdepartment=0 or isvirtualdepartment is null)  and (isoutdepartment=0 or isoutdepartment is null)";
                list = new EnttityBLL().GetEntitysBySqlComm<TreeViewData>(sql);
                rootlist = list.Where(p => p.Path == DeptPath).OrderBy(p => p.Path).ToList();
                int i = 0;
                if (rootlist != null)
                {
                    foreach (TreeViewData tree in rootlist)
                    {

                        _strHtml.Append("<ul id=\"test_tree_list\"><li>");
                     
                            _strHtml.Append(tree.Caption);
                         

                        //功能明细
                           AddNodeHtml(list, tree.Key, _strHtml);
                     
                        _strHtml.Append("</ul>");
                        i++;
                    }
                }
            return _strHtml.ToString();
        }

        private void AddNodeHtml(IList<TreeViewData> list, Guid? key, StringBuilder sb)
        {
            var detail = list.Where(p => p.ParentKey == key).OrderBy(p => p.Path).ToList();
            if (detail.ToList().Count > 0)
            {
                sb.Append("<ul>");
                sb.Append("<li></li>");
                foreach (TreeViewData v in detail)
                {
                    sb.Append("<li>");
              
                        sb.Append( v.Caption );
                        AddNodeHtml(list, v.Key, sb);
                    sb.Append("</li>");

                }
                sb.Append("</ul>");
            }
        }
    }
}
